<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Resource utils
 */

namespace crcl\base\resource;

interface IUtils
{
  /**
   * Return \TRUE if $sUri is a valid resource
   * just simple checks, should be more sophisticated?
   * @param string  $sUri
   */
  public static function isValid($sUri);

  /**
   * Returns scheme of uri
   * This method also exist in container objects
   *
   * @param string  $sUri URI
   * @return  string  Scheme
   */
  public static function getScheme($sUri);

  /**
   * Replaces scheme scheme of uri
   *
   * @param string  $sScheme Scheme
   * @param string  $sUri URI
   * @return  string  URI
   */
  public static function replaceScheme($sScheme, $sUri);
}

abstract class Utils implements IUtils
{
  public static function isValid($sUri)
  {
    $pos = \strpos($sUri, ':'); //URI = ://, URN = :
    if (($pos === \FALSE) || ($pos < 1))
    {
      return \FALSE;
    }
    if (isset($sUri[$pos+1]))
    {
      if ($sUri[$pos+1] == '\\') //:\\ typo
      {
        return \FALSE;
      }
    }
    return \TRUE;
  }

  public static function getScheme($sUri)
  {
    if (self::isValid($sUri))
    {
      $iPos = \strpos($sUri, ':');
      $sScheme = \substr($sUri, 0, $iPos);
      $sScheme = \trim($sScheme);
      $sScheme = \strtolower($sScheme);
      return $sScheme;
    }
    throw new Exception('No scheme',
      Exception::ERROR_RESOURCE_NOSCHEME, array('uri' => $sUri)
    );
  }

  public static function replaceScheme($sScheme, $sUri)
  {
    if (self::isValid($sUri))
    {
      $sScheme = \trim($sScheme);
      $sScheme = \strtolower($sScheme);

      $iPos = \strpos($sUri, ':');
      $sUri = \substr($sUri, $iPos);

      $sUri = $sScheme . $sUri;
      return $sUri;
    }
    throw new Exception('No scheme',
      Exception::ERROR_RESOURCE_NOSCHEME, array('uri' => $sUri)
    );
  }
}
